using UnityEngine;

namespace JufGame.MathHelper
{
	/// <summary>
	/// 指数移动平均线，用于预测数值变化趋势
	/// </summary>
	[System.Serializable]
	public class EMA
	{
		[SerializeField] private float k; // 收敛率
		private float lastValue = 0; // 上一个时间点的指数移动平均值
		/// <summary>
		/// 初始化指数移动平均线
		/// </summary>
		/// <param name="k">收敛率，越大通常导致变化越快</param>
		public EMA(float k)
		{
			this.k = k;
			lastValue = 0; // 初始化为0
		}
		public void SetK(float k)
		{
			this.k = k;
		}
		public float CalculateEMA(float newValue, float deltaTime)
		{
			// 计算指数移动平均
			var alpha = Mathf.Exp(-k * deltaTime);
			var ema = (1 - alpha) * newValue + alpha * lastValue;	
			// 更新上一个时间点的值
			lastValue = ema;
			return ema;
		}
	}
	public static class X_Space
	{
		/// <summary>
		/// 返回x = -log(1-p)
		/// </summary>
		public static float BaseLog(float p)
		{
			return - Mathf.Log(1 - p);
		}
		/// <summary>
		/// 返回p = 1 - e^(-p)
		/// </summary>
		public static float BaseX(float x)
		{
			return 1 - Mathf.Exp(-x);
		}
	}
}
